import { ref } from "vue";
import { http } from "@/utils/http";
import { getUserInfo as fetchUserInfo } from "@/api/user";

// 用户权限信息
interface UserPermission {
  accountId: number;
  nickName: string;
  email: string;
  rolePermission: {
    menu1List: Array<{
      menu1Id: number;
      menu1Name: string;
      menu1Key: string;
      menu2List: Array<{
        menu2Id: number;
        menu2Name: string;
        menu2Key: string;
        menu1Id: number;
        actionList: Array<{
          menu2Id: number;
          actionId: number;
          actionName: string;
          actionKey: string;
        }>;
      }>;
    }>;
  };
}

// 存储用户权限信息
const userPermission = ref<UserPermission | null>(null);

// 广告账户信息接口返回类型
interface AdAccount {
  adAccountId: number;
  adAccountName: string;
}

interface AdAccountResponse {
  code: number;
  msg: string;
  total: number;
  list: AdAccount[];
}

// 绑定广告账户请求参数类型
interface BindAdAccountRequest {
  accountId: number;
  adAccountList: {
    adAccountId: number;
    adAccountName: string;
  }[];
}

// 绑定广告账户响应类型
interface BindAdAccountResponse {
  code: number;
  msg: string;
}

// 绑定角色请求参数类型
interface BindRoleRequest {
  accountId: number;
  roleId: number;
}

// 绑定角色响应类型
interface BindRoleResponse {
  code: number;
  msg: string;
}

// 初始化用户权限
export const initUserPermission = async () => {
  try {
    const response = await fetchUserInfo();
    console.log("response", response);
    if (response) {
      // 处理rolePermission为null的情况，设置为空权限结构
      if (!response.rolePermission) {
        response.rolePermission = {
          menu1List: []
        };
      }
      userPermission.value = response;
    } else {
      console.error("获取用户权限失败: 响应数据格式错误");
      userPermission.value = null;
    }
  } catch (error) {
    console.error("获取用户权限失败:", error);
    userPermission.value = null;
  }
};

// 获取所有一级菜单键值
export const getAllMenu1Keys = (): string[] => {
  const permission = getUserPermission();
  if (!permission || !permission.rolePermission) return [];

  const { menu1List } = permission.rolePermission;
  return menu1List.map(menu1 => menu1.menu1Key);
};

// 获取所有二级菜单键值
export const getAllMenu2Keys = (): string[] => {
  const permission = getUserPermission();
  if (!permission || !permission.rolePermission) return [];

  const { menu1List } = permission.rolePermission;
  const menu2Keys: string[] = [];

  menu1List.forEach(menu1 => {
    menu1.menu2List.forEach(menu2 => {
      menu2Keys.push(menu2.menu2Key);
    });
  });

  return menu2Keys;
};

// 检查是否有某个菜单权限
export const hasMenuPermission = (menuKey: string): boolean => {
  console.log("检查菜单权限:", menuKey);
  const permission = getUserPermission();
  if (!permission || !permission.rolePermission) return false;

  const { menu1List } = permission.rolePermission;
  return menu1List.some(
    menu1 =>
      menu1.menu1Key === menuKey ||
      menu1.menu2List.some(menu2 => menu2.menu2Key === menuKey)
  );
};

// 检查是否有一级菜单权限
export const hasMenu1Permission = (menuKey: string): boolean => {
  const permission = getUserPermission();
  if (!permission || !permission.rolePermission) return false;

  const { menu1List } = permission.rolePermission;
  return menu1List.some(menu1 => menu1.menu1Key === menuKey);
};

// 检查是否有二级菜单权限
export const hasMenu2Permission = (menuKey: string): boolean => {
  const permission = getUserPermission();
  if (!permission || !permission.rolePermission) return false;

  const { menu1List } = permission.rolePermission;
  return menu1List.some(menu1 =>
    menu1.menu2List.some(menu2 => menu2.menu2Key === menuKey)
  );
};

// 检查是否有某个操作权限
export const hasActionPermission = (actionKey: string): boolean => {
  console.log("检查操作权限:", actionKey);
  const permission = getUserPermission();
  if (!permission || !permission.rolePermission) return false;

  const { menu1List } = permission.rolePermission;
  return menu1List.some(menu1 =>
    menu1.menu2List.some(menu2 =>
      menu2.actionList.some(action => action.actionKey === actionKey)
    )
  );
};

// 获取用户权限列表
export const getUserPermission = () => {
  // 如果权限尚未初始化，使用硬编码的测试数据
  if (!userPermission.value) {
    console.log("使用硬编码的测试权限数据");
    return {
      accountId: 1,
      nickName: "测试用户",
      email: "test@example.com",
      rolePermission: {
        menu1List: [
          {
            menu1Id: 2,
            menu1Name: "推广",
            menu1Key: "promotion",
            menu2List: [
              {
                menu2Id: 1,
                menu2Name: "广告计划",
                menu2Key: "advertising_plan",
                menu1Id: 2,
                actionList: [
                  {
                    menu2Id: 1,
                    actionId: 2,
                    actionName: "广告计划列表",
                    actionKey: "advertising_plan_list"
                  },
                  {
                    menu2Id: 1,
                    actionId: 3,
                    actionName: "广告计划开启",
                    actionKey: "advertising_plan_openStatus"
                  },
                  {
                    menu2Id: 1,
                    actionId: 4,
                    actionName: "广告计划关闭",
                    actionKey: "advertising_plan_closeStatus"
                  },
                  {
                    menu2Id: 1,
                    actionId: 5,
                    actionName: "广告计划删除",
                    actionKey: "advertising_plan_delete"
                  }
                ]
              },
              {
                menu2Id: 2,
                menu2Name: "广告组",
                menu2Key: "advertising_group",
                menu1Id: 2,
                actionList: [
                  {
                    menu2Id: 2,
                    actionId: 6,
                    actionName: "广告组列表",
                    actionKey: "advertising_group_list"
                  },
                  {
                    menu2Id: 2,
                    actionId: 7,
                    actionName: "广告组开启",
                    actionKey: "advertising_group_openStatus"
                  },
                  {
                    menu2Id: 2,
                    actionId: 8,
                    actionName: "广告组关闭",
                    actionKey: "advertising_group_closeStatus"
                  },
                  {
                    menu2Id: 2,
                    actionId: 9,
                    actionName: "广告组删除",
                    actionKey: "advertising_group_delete"
                  }
                ]
              },
              {
                menu2Id: 3,
                menu2Name: "广告创意",
                menu2Key: "advertising_creative",
                menu1Id: 2,
                actionList: [
                  {
                    menu2Id: 3,
                    actionId: 10,
                    actionName: "广告创意列表",
                    actionKey: "advertising_creative_list"
                  },
                  {
                    menu2Id: 3,
                    actionId: 11,
                    actionName: "广告创意开启",
                    actionKey: "advertising_creative_openStatus"
                  },
                  {
                    menu2Id: 3,
                    actionId: 12,
                    actionName: "广告创意关闭",
                    actionKey: "advertising_creative_closeStatus"
                  },
                  {
                    menu2Id: 3,
                    actionId: 13,
                    actionName: "广告创意删除",
                    actionKey: "advertising_creative_delete"
                  }
                ]
              }
            ]
          },
          {
            menu1Id: 5,
            menu1Name: "权限管理",
            menu1Key: "permission_management",
            menu2List: [
              {
                menu2Id: 7,
                menu2Name: "权限管理",
                menu2Key: "permission_management",
                menu1Id: 5,
                actionList: [
                  {
                    menu2Id: 7,
                    actionId: 17,
                    actionName: "权限管理列表",
                    actionKey: "permission_management_list"
                  },
                  {
                    menu2Id: 7,
                    actionId: 18,
                    actionName: "权限管理-添加人员",
                    actionKey: "permission_management_addUser"
                  },
                  {
                    menu2Id: 7,
                    actionId: 19,
                    actionName: "权限管理-权限配置",
                    actionKey: "permission_management_setPermission"
                  },
                  {
                    menu2Id: 7,
                    actionId: 20,
                    actionName: "权限管理-分配广告账户",
                    actionKey: "permission_management_addAdAccount"
                  },
                  {
                    menu2Id: 7,
                    actionId: 21,
                    actionName: "权限管理-删除用户",
                    actionKey: "permission_management_deleteUser"
                  }
                ]
              }
            ]
          }
        ]
      }
    };
  }

  return userPermission.value;
};

// 获取广告账户列表
export const getAdAccountList = async (
  page: number,
  size: number
): Promise<AdAccountResponse> => {
  try {
    const response = await http.get<AdAccountResponse, any>(
      "/api/v1/system/all/adAccount",
      {
        params: {
          page,
          size
        }
      }
    );
    return response;
  } catch (error) {
    console.error("获取广告账户列表失败:", error);
    throw error;
  }
};

// 绑定广告账户
export const bindAdAccount = async (
  params: BindAdAccountRequest
): Promise<BindAdAccountResponse> => {
  try {
    const response = await http.post<BindAdAccountResponse, any>(
      "/api/v1/account/bind/adAccount",
      {
        data: params
      }
    );
    return response;
  } catch (error) {
    console.error("绑定广告账户失败:", error);
    throw error;
  }
};

// 绑定角色
export const bindRole = async (
  params: BindRoleRequest
): Promise<BindRoleResponse> => {
  try {
    const response = await http.post<BindRoleResponse, any>(
      "/api/v1/account/bind/role",
      {
        data: params
      }
    );
    return response;
  } catch (error) {
    console.error("绑定角色失败:", error);
    throw error;
  }
};
